<template>
  <div>
    <a-modal
        :width="1200"
        :visible="visible"
        centered
        @cancel="onClose"
        :footer="null"
        :bodyStyle="{
          padding: '0'
        }"
    >
      <div class="content">
        <a-spin
            tip="正在加载中..."
            :spinning="spinLoding"
            :style="{ height: spinHeight }"
        >
          <iframe
              v-if="previewUrl"
              :height="clientHeight * 0.85"
              width="100%"
              :src="previewUrl"
              allowtransparency="true"
              allowfullscreen="true"
              allowfullscreenInteractive="true"
              scrolling="no"
              border="0"
              frameborder="0"
              @load="handleLoad"
          ></iframe>
        </a-spin>
      </div>
      <template #title>
        <a-space>
          <div style="margin-right: 10px">{{ title }}</div>
          <div v-if="!esignDetail.esignCheck">
            <a-space>
              <a-button
                  type="primary"
                  v-for="item in operateButList"
                  :key="item.key"
                  @click="operateClick(item)"
                  :loading="item.btnLoading"
                  v-show="operateButton.includes(item.key)"
              >{{ item.title }}
              </a-button>
            </a-space>
          </div>
          <div v-if="esignDetail.esignCheck">
            <a-space>
              <a-button
                  v-if="fileUrl"
                  type="primary"
                  @click="operateClick('esignCheck')"
              >
                <DownloadOutlined/>
                文档下载
              </a-button>
              <a-button v-if="canPrint" type="primary" @click="printFile">
                <PrinterOutlined/>
                文档打印
              </a-button>

              <a-button
                  v-if="signStatus == 2"
                  type="primary"
                  :loading="operateLoading"
                  @click="operateClick('signing')"
              >
                <EditOutlined/>
                重新签约
              </a-button>
            </a-space>
          </div>
        </a-space>
      </template>
    </a-modal>

    <EsignStamp
        :esignVisible="esignStampVisible"
        @close="esignStampVisible = false"
        @success="esignStampSuccess"
    />

    <!-- 发起电签 loading -->
    <div class="el-loading" v-if="elSignLoading">
      <a-spin tip="发起电子签约中，请稍加等待..."/>
    </div>

    <!-- 二维码签约 -->
    <QrCode
        :visible="qrCodeVisible"
        :qrcodeUrl="qrcodeUrl"
        @close="qrCodeVisible = false"
    />

    <!--打印-->
    <print-modal :file_list="printList" :usePrint="showModal" @change="showModal=false"/>


  </div>
</template>

<script>
import {computed, defineComponent, reactive, toRefs, watch} from "vue";
import request from "../../common/utils/request";

import EsignStamp from "./EsignStamp.vue";
import {useRoute, useRouter} from "vue-router";
import QrCode from "./QrCode.vue";
import {message, Modal} from "ant-design-vue";
import {
  CloudDownloadOutlined,
  DownloadOutlined,
  EditOutlined,
  PrinterOutlined,
} from "@ant-design/icons-vue";
import axios from "axios";
import PrintModal from '@/components/Bill/PrintModal.vue'

export default defineComponent({
  name: "EsignStamps",
  components: {
    PrintModal,
    CloudDownloadOutlined,
    EsignStamp,
    QrCode,
    DownloadOutlined,
    EditOutlined,
    PrinterOutlined,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    contractBasicInfo: {
      type: Object,
      default: () => {
        return {};
      },
    },
    esignDetail: {
      type: Object,
      default: () => {
        return {};
      },
    },
    title: {
      type: String,
      default: "电子合同",
    },
    urlData: {
      type: Object,
      default: () => {
        return {};
      },
    },
    type: {
      type: String,
      default: "",
    },
    showType: {
      type: String,
      default: "",
    },
    drawerId: {
      type: [Number, String],
      default: "",
    },
  },
  setup(props, {emit}) {
    const router = useRouter();
    const route = useRoute();
    const id = computed(() =>
        props.showType === "drawer"
            ? Number(props.drawerId)
            : Number(route.query.id)
    );

    const state = reactive({
      sign_type: "1",
      esignStampVisible: false,
      elSignLoading: false,
      qrCodeVisible: false,
      qrcodeUrl: "",
      previewUrl: "",
      operateButton: [],
      operateButList: [
        {
          title: "发送到租客手机签约",
          key: "SEND_NOTICE",
          btnLoading: false,
        },
        {
          title: "二维码现场扫描签约",
          key: "SCAN_NOTICE",
          btnLoading: false,
        },
      ],
      fileUrl: "",
      clientHeight: document.body.clientHeight,

      operateLoading: false,

      signStatus: 0,

      spinLoding: true,
      showModal: false,
      canPrint: false,
      printList: [],
    });

    const esignClick = () => {
    };

    const esignStampSuccess = (sign_type) => {
      state.esignStampVisible = false;
      state.elSignLoading = true;
      let params = {
        contract_id: id.value,
      };
      if (sign_type) {
        params.sign_type = sign_type;
      }
      state.operateButList[0].btnLoading = true;
      request
          .get("/org", "/esign/uploadContract", params)
          .then((res) => {
            getElectronSign();
            state.operateButList[0].btnLoading = false;
            Modal.info({
              title: () => "提示",
              centered: true,
              content: () =>
                  h("div", [
                    h(
                        "p",
                        "电子合同签约发起成功！签约短信已下发到租客手机，请提醒租客点击短信进行签约。"
                    ),
                    h("p", "最终签约结果系统将通过站内通知告知您。"),
                  ]),
            });
          })
          .finally(() => {
            state.operateButList[0].btnLoading = false;
            emit("refresh");
            state.elSignLoading = false;
          });
    };

    const operateClick = (item) => {
      // 重新签约
      if (item == "signing") {
        state.operateLoading = true;
        request
            .get("/org", "/contract/electronSign/init", {
              contract_id: props.contractBasicInfo.id,
              apply_template_id: props.contractBasicInfo.apply_template_id,
            })
            .then((res) => {
              state.operateLoading = false;
              request
                  .put("/org", "/electronSign/sendNotice", {
                    contract_id: props.contractBasicInfo.id,
                  })
                  .then((res) => {
                    message.success("已重新签约");
                    emit("refresh");
                  })
                  .finally(() => {
                  });
            });

        return;
      }
      // 查看电子合同 下载
      if (item == "esignCheck") {
        window.open(state.fileUrl);
        return;
      }

      // 发送到租客手机签约
      if (item.key == "SEND_NOTICE") {
        if (props.esignDetail.type == 0) {
          if (props.contractBasicInfo.sign_status == 1) {
            // 签署中
            Modal.info({
              title: () => "提示",
              centered: true,
              content: () =>
                  "您已发起过电子合同签约，请耐心等待签约结果，最终签约结果系统将通过站内通知告知您。",
            });
          } else {
            // 可以发起签署
            // 获取电子合同设置
            if (
                props.esignDetail &&
                props.esignDetail.sign_type &&
                props.esignDetail.sign_type.length > 0
            ) {
              if (props.esignDetail.sign_type.length > 1) {
                // 盖章方式超过一种时，弹窗让用户选择
                // esignStampVisible.value = true;
                state.esignStampVisible = true;
              } else {
                esignStampSuccess(props.esignDetail.sign_type[0]);
              }
            }
          }
          return;
        }
        if (props.esignDetail.type == 1) {
          if (props.contractBasicInfo.sign_status == 1) {
            // 签署中
            Modal.info({
              title: () => "提示",
              centered: true,
              content: () =>
                  "您已发起过电子合同签约，请耐心等待签约结果，最终签约结果系统将通过站内通知告知您。",
            });
            return;
          }
          item.btnLoading = true;
          request
              .put("/org", "/electronSign/sendNotice", {
                contract_id: props.contractBasicInfo.id,
              })
              .then((res) => {
                message.success("发送成功");
                item.btnLoading = false;
                emit("refresh");
              })
              .finally(() => {
                item.btnLoading = false;
              });
        }
        return;
      }
      state.qrCodeVisible = true;
    };

    const getElectronSign = () => {
      request
          .get("/org", "/electronSign/get", {
            contract_id: props.contractBasicInfo.id,
          })
          .then((res) => {
            state.previewUrl = res.result.previewUrl;
            state.qrcodeUrl = res.result.h5_url;
            state.operateButton = res.result.operate_button;
            state.fileUrl = res.result.fileUrl;
            state.signStatus = res.result.sign_status;
          });
    };

    const onClose = () => {
      emit("close");
    };

    const handleLoad = () => {
      state.spinLoding = false;
    };

    const spinHeight = computed(() => {
      return state.clientHeight * 0.85 + "px";
    });

    watch(
        () => props.visible,
        (val) => {
          if (val) {
            if (props.urlData.previewUrl) {
              state.previewUrl = props.urlData.previewUrl;
              state.fileUrl = props.urlData.url;
              if (state.fileUrl.endsWith(".docx")) {
                state.canPrint = true;
              }
              return;
            }
            if (props.type == "contractDetail" && !props.urlData.previewUrl) {
              getElectronSign();
            }
          } else {
            state.previewUrl = "";
            state.qrcodeUrl = "";
            state.signStatus = 0;
          }
        }
    );

    const printFile = () => {
      state.printList = [state.fileUrl];
      state.showModal = true;
    }

    return {
      ...toRefs(state),
      onClose,
      esignClick,
      esignStampSuccess,
      operateClick,
      spinHeight,
      handleLoad,
      printFile,
    };
  },
});
</script>

<style lang="less" scoped>
.content {
  width: 100%;
  display: flex;
  justify-content: center;
}

.el-loading {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.6);
}

:deep(.ant-spin-nested-loading) {
  width: 100%;
}
</style>
